import { serverUrl } from "../config/env";
import { login } from "./user";

export default class Base {
  constructor(baseUrl) {
    this.baseUrl = baseUrl || serverUrl;
  }
  request(url, method, data, config) {
    const that = this
    return new Promise((resolve, reject) => {
      wx.request({
        url: this.baseUrl + url,
        method: method,
        data: data,
        header: Object.assign(
          {
            "content-type": "application/json", // 默认值
            token: wx.getStorageSync("token"),
          },
          config
        ),
        async success(res) {
          if (res.statusCode === 200) {
            if (res.data.code === 0) {
              resolve(res.data.data);
            } else if (res.data.code === 1) {
              await that.refreshToken()
              that.request(url, method, data, config)
            }
          } else {
            reject(res);
          }
        },
        fail(res) {
          reject(res);
        },
      });
    });
  }
  get(url, data) {
    return this.request(url, "GET", data);
  }
  post(url, data) {
    return this.request(url, "POST", data);
  }
  postform(url, data) {
    return this.request(url, "POST", data, {
      "content-type": "application/x-www-form-urlencoded", // 默认值
    });
  }
  delete(url, data) {
    return this.request(url, "DELETE", data);
  }
  put(url, data) {
    return this.request(url, "PUT", data);
  }
  refreshToken() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: async (res) => {
          const token = await login(res.code);
          wx.setStorageSync("token", token);
          resolve(token)
        },
      });
    });
  }
}
